from core.utils import render_to
from django.core import serializers

from django.shortcuts import redirect

from datetime import date

from django.contrib.auth.models import User
from exams.models import Exam, Professor, Subject, SubjectYear, ExamApplication, SubjectParticipant, Executor
from core.models import Post, Commune, Program, CourseGroup
from student.models import EnrollmentSheet, Student
import datetime
from django.contrib.auth.decorators import login_required
from exams.forms import ExamFormApplication, CardListSelection, InputExamSelection, ViewExams, ExamSelection, ExamForm
from django import forms
from django.contrib.auth.decorators import permission_required
from django.http import Http404, HttpResponse
from django.conf import settings
from django.db.models import Q
from django.utils.datastructures import DotExpandedDict
import json

@login_required
@render_to('exams/exam_list.htm')
def exam_list(request, professor = None, selected_exam=None):
  form = ExamSelection()
  
  professorObj = None
  try:
    if (request.user.professor):
      professorObj = request.user.professor
      if not professor:
        redirect("/exams/exam_list/"+str(professorObj.pk)+"/")
  except Exception,e:
    print e
    if not professor:
      return {"only_search":True}
    professorObj = Professor.objects.get(pk = professor )
    
  form.fields['exam'].queryset = Exam.for_professor(professorObj).filter(special=False).order_by("date")
  form.fields["exam"].initial = selected_exam
  
  
  data = None
  exam = None
  execs = None
  if selected_exam != None:
    exam = Exam.objects.get(pk = selected_exam)
    data = ExamApplication.objects.filter(exam = selected_exam).order_by("student__user__last_name","student__user__first_name")
    execs = exam.executor
  
  if data:
    for examapp in data:
      queryset_exam_subject = exam.subject.subject
      examapp.num_app = queryset_exam_subject.number_applies_str(examapp.student)
  
  return {"professor":professorObj, "form":form, "selected_exam":selected_exam,"data":data,"exam":exam, "execs":execs}

@login_required
@render_to('exams/exam_partial_list.htm')
def exam_partial_list(request, professor = None, selected_exam=None):
  form = ExamSelection()
 
  professorObj = None
  try:
    if (request.user.professor):
      professorObj = request.user.professor
      if not professor:
        redirect("/exams/exam_partial_list/"+str(professorObj.pk)+"/")
  except Exception,e:
    print e
    if not professor:
      return {"only_search":True}
    professorObj = Professor.objects.get(pk = professor )
    
  form.fields['exam'].queryset = Exam.for_professor(professorObj).filter(date__lte=date.today(),special=False).order_by("date")
  form.fields["exam"].initial = selected_exam
  
  data = None
  exam = None
  execs = None
  if selected_exam != None:
    exam = Exam.objects.get(pk = selected_exam)
    data = ExamApplication.objects.filter(exam = selected_exam).order_by("student__user__last_name","student__user__first_name")
    execs = exam.executor
  
  if data:
    for examapp in data:
      queryset_exam_subject = exam.subject.subject
      examapp.num_app = queryset_exam_subject.number_applies_str(examapp.student)
  
  return {"professor":professorObj,"form":form, "selected_exam":selected_exam,"data":data,"exam":exam, "execs":execs}
  
  
@login_required
@render_to('exams/exam_final_list.htm')
def exam_final_list(request, professor = None, selected_exam=None):
  form = ExamSelection()
  
  professorObj = None
  try:
    if (request.user.professor):
      professorObj = request.user.professor
      if not professor:
        redirect("/exams/exam_final_list/"+str(professorObj.pk)+"/")
  except Exception,e:
    print e
    if not professor:
      return {"only_search":True}
    professorObj = Professor.objects.get(pk = professor )
    
  form.fields['exam'].queryset = Exam.for_professor(professorObj).filter(date__lte=date.today(),special=False).order_by("date")
  form.fields["exam"].initial = selected_exam
  
  
  data = None
  exam = None
  execs = None
  if selected_exam != None:
    exam = Exam.objects.get(pk = selected_exam)
    data = ExamApplication.objects.filter(exam = selected_exam).order_by("student__user__last_name","student__user__first_name")
    execs = exam.executor
  
  if data:
    for examapp in data:
      queryset_exam_subject = exam.subject.subject
      examapp.num_app = queryset_exam_subject.number_applies_str(examapp.student)
  return {"professor":professorObj, "form":form, "selected_exam":selected_exam,"data":data,"exam":exam, "execs":execs} #, "applies":list(appList)

  
  
@login_required
@render_to('exams/input_wgrade.htm')
def input_wgrade(request, professor=None, selected_exam=None):
  form = ExamSelection()
  
  professorObj = None
  try:
    if (request.user.professor):
      professorObj = request.user.professor
      if not professor:
        redirect("/exams/wgrade/"+str(professorObj.pk)+"/")
  except Exception,e:
    print e
    if not professor:
      return {"only_search":True}
    professorObj = Professor.objects.get(pk = professor )
    
  form.fields['exam'].queryset = Exam.for_professor(professorObj).filter(date__lte=date.today(),special=False).order_by("date")
  form.fields["exam"].initial = selected_exam
  
  
  data = None
  exam = None
  saved = None
  if request.method == 'POST':
    d = DotExpandedDict(request.POST)
    for a in d['application']:
      points = d['application'][a].get("points")
      points_rest = d['application'][a].get("points_rest")
      vp = d['application'][a].get("vp")
      application = ExamApplication.objects.get(pk=a)
      if points:
        application.points = points
      if points_rest:
        application.points_rest = points_rest
        
      if vp == "1":
        application.exam_grade = 0
        application.practice_grade = 0
      else:
        if application.exam_grade == 0:
          application.exam_grade = None
        if application.practice_grade == 0:
          application.practice_grade = None
      application.save()
      saved = True
      
  if selected_exam != None:
    exam = Exam.objects.get(pk = selected_exam)
    data = ExamApplication.objects.filter(exam = selected_exam).order_by("student__user__last_name","student__user__first_name")
 
  if data:
    for d in data:
      d.num_app = exam.subject.subject.number_applies_str(d.student)
  
  return {"saved":saved,"form":form, "selected_exam":selected_exam,"data":data,"exam":exam, "professor":professorObj}

@login_required
@render_to('exams/input_grade.htm')
def input_grade(request, professor=None, selected_exam=None):
  form = ExamSelection()
  
  professorObj = None
  try:
    if (request.user.professor):
      professorObj = request.user.professor
      if not professor:
        redirect("/exams/grade/"+str(professorObj.pk)+"/")
  except Exception,e:
    print e
    if not professor:
      return {"only_search":True}
    professorObj = Professor.objects.get(pk = professor )
    
  form.fields['exam'].queryset = Exam.for_professor(professorObj).filter(date__lte=date.today(),special=False).order_by("date")
  form.fields["exam"].initial = selected_exam
  
  
  data = None
  exam = None
  saved = None
  if request.method == 'POST':
    d = DotExpandedDict(request.POST)
    for a in d['application']:
      exam_grade = d['application'][a].get("exam_grade")
      practice_grade = d['application'][a].get("practice_grade")
      vp = d['application'][a].get("vp")
      application = ExamApplication.objects.get(pk=a)
      if exam_grade and application.exam_grade != exam_grade:
        application.exam_grade = exam_grade
        application.grade_date = date.today()
      if practice_grade and application.practice_grade != practice_grade:
        application.practice_grade = practice_grade
        application.grade_date = date.today()
      if vp == "1":
        application.exam_grade = 0
        application.practice_grade = 0
      else:
        if application.exam_grade == 0:
          application.exam_grade = None
        if application.practice_grade == 0:
          application.practice_grade = None        
      application.save()
      saved = True
      
  if selected_exam != None:
    exam = Exam.objects.get(pk = selected_exam)
    data = ExamApplication.objects.filter(exam = selected_exam).order_by("student__user__last_name","student__user__first_name")
 
  if data:
    for d in data:
      d.num_app = exam.subject.subject.number_applies_str(d.student)  
  return {"saved":saved,"form":form, "selected_exam":selected_exam,"data":data,"exam":exam, "professor":professorObj}
  
# This is an empty simple view, to avoid errors
@login_required
@permission_required('student.can_card_index')
@render_to('exams/card_index.htm')
def card_index(request,id=None):
  try:
    student = request.user.student
  except:
    if id == None:
      return {"only_search":True}
    student = Student.objects.get(pk=id) 
  if request.method == 'POST':
    step = int(request.POST["step"])
    if step == 1:
      form = CardListSelection(request.POST,student=student)
      form.is_valid()
      #build data for display
      data = []
      try:
        es = EnrollmentSheet.objects.filter(student=student)
        if not form.cleaned_data['program'] == '0':
          es = es.filter(student_program=form.cleaned_data['program'])
        es = es.order_by('student_program').order_by('-student_year').order_by("-academic_year")
      except:
         raise Http404()
      prev_es_year = None
      for e in es:
        d = {"e":e}
        d["subjects"] = []
        subjects = SubjectParticipant.objects.filter(Q(Q(subject__subject__subjectprogram__year__exact=e.student_year) | Q(subject__subject__subjectprogram__year__isnull=True)),Q(student=student,subject__school_year_start=e.academic_year_start(),subject__school_year_end=e.academic_year_end()))
        for s in subjects:
          d_s = {"sp":s}
          #izpiti
          apps = ExamApplication.objects.filter(exam__subject__subject=s.subject.subject,student=student)
          apps = apps.exclude(exam_grade=0,practice_grade=0)
          apps = apps.filter(exam__subject__school_year_start__gte=s.subject.school_year_start)
          if prev_es_year:
            apps = apps.filter(exam__subject__school_year_end__lte=prev_es_year)
          apps = apps.order_by('exam__date','pk')
          acounter = {}
          for a in apps:
            till_date = a.exam.date
            a.try_ = a.exam.number_applies_till_date(student,till_date,a.pk)
            key = str(a.exam.date_to_school_year())
            if not acounter.has_key(key):
              acounter[key] = 0
            acounter[key] = acounter[key] + 1
            a.count_year = acounter[key]
           
          #hack for slice to show only last exam
          if not int(form.cleaned_data['view']) == 1 and apps:
            tmp = [a for a in apps]
            apps = [tmp[-1]]
          d_s["apps"] = apps
          d["subjects"].append(d_s)
        #ce ponavlja ta letnik, bo naslednji imel omejitev do tega leta, drugace je omejitev v neskocno
        if e.enrollment_type == 'V2':
          prev_es_year = s.subject.school_year_start
        data.append(d)
        
      for d in data:
        #calculate average
        count_wgrade = 0.0
        count_ograde = 0.0
        sum_wgrade = 0
        sum_ograde = 0
        credit_points = 0
        all_credit_points = 0
        for s in d['subjects']:
          all_credit_points = all_credit_points + s['sp'].subject.subject.credit_points
          e_done = False
          for a in s['apps']:    
            if a.exam.rating_type == 'OC1' or a.exam.rating_type == 'OC3':
              if a.exam_grade >= settings.POSITIVE_GRADE_BOUNDARY:
                count_wgrade = count_wgrade + 1.0
                sum_wgrade = sum_wgrade + a.exam_grade
                e_done = True
            if a.exam.rating_type == 'OC1' or a.exam.rating_type == 'OC2':  
              if a.practice_grade >= settings.POSITIVE_GRADE_BOUNDARY:
                count_ograde = count_ograde + 1.0
                sum_ograde = sum_ograde + a.practice_grade
                e_done = True
          if e_done == True:
            credit_points = credit_points + s['sp'].subject.subject.credit_points
        
        avg_wgrade = None
        avg_ograde = None
        if count_wgrade > 0:
          avg_wgrade = sum_wgrade / count_wgrade
        if count_ograde > 0:
          avg_ograde = sum_ograde / count_ograde
        d["avg_wgrade"] = avg_wgrade
        d["avg_ograde"] = avg_ograde
        if avg_wgrade and avg_ograde:
          d["avg_grade"] = (avg_wgrade+avg_ograde) / 2.0
        d["all_credit_points"] = all_credit_points
        d["credit_points"] = credit_points
      return {"step":1,"data":data,"student":student,"parameters":{
        "step": 1,
        "view": form.cleaned_data['view'],
        "program": form.cleaned_data['program'],
      }}

    else:
     cardListSelection = CardListSelection(student=student)
     return {"cardListSelection":cardListSelection,"step":0,"step_next":1,"student":student}
  else:
    cardListSelection = CardListSelection(student=student)
    return {"cardListSelection":cardListSelection,"step":0,"step_next":1,"student":student}


@login_required
@render_to('exams/exam_application.htm')
def exam_application(request, student_pk=None):
  error = False
  threeTimes = False
  sixTimes = False
  save = False #if application is saved
  status = True #if has status
  numberApplys_all = []
  numberApplys = 0
  only_search = False
  student = None
  referent = False
  warning = False
  
  ref_past = False 
  ref_done = False 
  ref_3days = False 
  ref_3times = False
  ref_6times = False 
  ref_14days = False
  
  step = 1
  list = []
  exam_pk = 0
  paid = False
  
  repeatsYear = False
  try:
    #get current student
    student = request.user.student
    if student.latest_enrollment_sheet.enrollment_type == settings.ENROLLMENT_TYPES[1][0]:
      repeatsYear = True
      
  except:
    if student_pk != None:
      student = Student.objects.get(pk = student_pk)
      referent = True
    else:
      only_search = True
  
  date_today = datetime.date.today()
  school_year_start = school_start_year()
  
  #get passed subjects
  queryset_passed_exams = ExamApplication.objects.values('exam').filter(Q(student = student), (Q(exam_grade__gte = settings.POSITIVE_GRADE_BOUNDARY) | Q(practice_grade__gte = settings.POSITIVE_GRADE_BOUNDARY)))
  queryset_passed_ex = Exam.objects.values('subject').filter(pk__in = queryset_passed_exams)
  queryset_passed_subjects_year = SubjectYear.objects.values('subject').filter(pk__in = queryset_passed_ex)
  queryset_passed_subjects = Subject.objects.filter(pk__in = queryset_passed_subjects_year)
  print "Passed subjects %s" %queryset_passed_subjects
  
  queryset_applied_exams_apl = ExamApplication.objects.filter(student = student, exam_grade = None)
  print "Applied: %s" %queryset_applied_exams_apl
  
  #get subjects for current student
  queryset_subject_part = SubjectParticipant.objects.values('subject').filter(student = student) 
  queryset_subject_year = SubjectYear.objects.values('subject').filter(pk__in = queryset_subject_part)
  queryset_subject = Subject.objects.filter(pk__in = queryset_subject_year)
  
  if not referent:
     #exclude passed subjects
    queryset_subject = queryset_subject.exclude(pk__in = queryset_passed_subjects)
    print queryset_subject
    
  #exclude applied subjects
  for i in queryset_applied_exams_apl:
    queryset_subject = queryset_subject.exclude(pk = i.exam.subject.subject.pk)

  queryset_subject_year = SubjectYear.objects.filter(subject__in=queryset_subject, school_year_start = school_year_start)
  queryset_subject_year = queryset_subject_year.order_by('subject__subjectprogram__year', 'subject__name')  


  queryset_subject_temp = queryset_subject
  
  for i in queryset_subject_temp:
    counter = 0
    queryset_exams = Exam.objects.filter(subject__subject__pk = i.pk)

    if len(queryset_exams) > 0:
      counter = queryset_exams[0].number_applies_this_year(student)
      
    #exclude subjects with too many applications this year
    if not referent:
      if counter >= 3:
        queryset_subject_year = queryset_subject_year.exclude(subject__pk = i.pk)
  #--------------------------------------------------------------    
  if request.method == 'POST':
    step = int(request.POST["step"])
    
    #referent confirm apply
    if referent and step == 2:
      step=1
      
      id = request.POST["exam"]
      exam = Exam.objects.get(pk = id)
      get_paid = request.POST["paid"]
      
      if get_paid == "False":
        get_paid = False
      elif get_paid == "True":
        get_paid = True  
      
      exam_apply = ExamApplication(
            exam = exam, 
            student = student, 
            application_date = datetime.date.today(),
            paid = get_paid
          )
      
      exam_apply.save()
      save = True 
      
      form = ExamFormApplication()
      queryset_subject_year = queryset_subject_year.exclude(subject__pk = exam.subject.subject.pk)
      form.fields['exam'].queryset = queryset_subject_year    
    
    else:
      form = ExamFormApplication(request.POST)
      
      #it works, but it's not optimal
      form.fields['exam'].queryset = queryset_subject_year
      form.fields['date'].choices = [(i.pk, i.pk) for i in Exam.objects.all()] 
      
      if form.is_valid():
        
        #get selected exam and date from form  
        form_exam = form.cleaned_data['exam']
        form_date = form.cleaned_data['date']
        
        #check status
        if school_start_year() != student.latest_enrollment_sheet.academic_year_start():
          status = False
          warning = True
          paid = True
        
        #get selected exam and number of applications for this exam
        exam = Exam.objects.filter(subject__subject = form_exam.subject, date = Exam.objects.get(pk = form_date).date)[0]
        
        #get all exams for selected subject
        queryset_exam_subject = Subject.objects.get(pk = form_exam.subject.pk)
          
        numberApplys_all = queryset_exam_subject.number_applies(student)
        numberApplys_all[0] = numberApplys_all[0] + 1
        numberApplys = numberApplys_all[0] - numberApplys_all[1] 
        print "Applies: %s" %numberApplys 
         
        if(exam.date < datetime.date.today()):
          print "prijava na pretekli izpit"
          ref_past = True
          warning = True
        
        queryset_already_passed = queryset_passed_subjects.filter(pk = exam.subject.subject.pk)   
        if len(queryset_already_passed) > 0:
          print "prijava na ze opravljen izpit"
          ref_done = True 
          warning = True
        
        if not exam.check_exam_date():
          if not ref_past == True:
            ref_3days = True
            warning = True
        
        if numberApplys > 6:
          ref_6times = True
          warning = True
        
        if exam.number_applies_this_year(student) >= 3:
          ref_3times = True
          warning = True
        
        if exam.check_14_days(student) == False:
          ref_14days = True
          warning = True     
        
        # if > 3 then you have to pay
        if numberApplys > 3:
          threeTimes = True
          warning = True
          paid = True  
          
        #if <= 6 then it's ok
        if numberApplys <= 6 and not referent:
          exam_apply = ExamApplication(
            exam = exam, 
            student = student, 
            application_date = datetime.date.today(),
            paid = paid
          )
          
          exam_apply.save()
          save = True
          
        elif referent:
          step = 2
          
          list = []
          tempList = []
          tempList.append(exam.pk)
          tempList.append(exam.subject.subject)  
          tempList.append(exam.show_professor())
          tempList.append(exam.date)
          
          if exam.time == datetime.time(0,0,0):
            tempList.append("")
          else:  
            tempList.append(exam.time)
        
          tempList.append(exam.place)
          tempList.append(exam.num_students())
          
          list = tempList
          
          exam_pk = exam.pk
          
        else:
          sixTimes = True
      
      else:
        form.fields["exam"].queryset = queryset_subject_year
    
  else:
    
    form = ExamFormApplication()
    
    form.fields['exam'].queryset = queryset_subject_year
    
  return {
    "examFormApplication":form,
    "threeTimes":threeTimes,
    "sixTimes":sixTimes,
    "numberApplys":numberApplys_all,
    "numberApplysCalculated":numberApplys,
    "status":status,
    "save":save, 
    "only_search":only_search,
    "referent":referent,
    "warning":warning,
    "ref_past":ref_past, "ref_done":ref_done, "ref_3days":ref_3days,
    "ref_14days":ref_14days, "ref_3times":ref_3times, "ref_6times":ref_6times,
    "step_next":step,
    "list":list,
    "get_exam":exam_pk,
    "student":student,
    "paid":paid
    }

@login_required
@render_to('exams/modify_exam.htm')
def modify_exam(request, professor = None, selected_exam=None):
  form = ExamSelection()
  professorObj = None
  try:
    if request.user.professor:
      profi = request.user.professor
  except:
      profi = ''
      
  professorObj = None
  limitProf = None
  try:
    if (request.user.professor):
      professorObj = request.user.professor
      profi = request.user.professor
      if not professor:
        redirect("/exams/modify_exam/"+str(professorObj.pk)+"/")
      limitProf = professorObj
  except Exception,e:
    profi = ''
    if not professor:
      return {"only_search":True}
    professorObj = Professor.objects.get(pk = professor )
    
  form.fields['exam'].queryset = Exam.for_professor(professorObj).filter(special=False).order_by("date")
  form.fields["exam"].initial = selected_exam
  
  win = '';
  exam = None
  formsubmit = '';
  final='wakka'
  if selected_exam:
    formsubmit = 'submit'
    if request.method == 'POST':
      exam = Exam.objects.get(pk=selected_exam)
      form = ExamForm(request.POST, instance=exam, subject=exam.subject, professor=limitProf)
      form.fields['id'].widget.attrs['readonly'] = True
      form.fields['special'].widget.attrs['hidden'] = True
      form.fields['subject'].widget.attrs['hidden'] = True
      if form.is_valid():
        form.save()
        win = "Izpitni rok je bil modificiran!";
    else:
      exam = Exam.objects.get(pk=selected_exam)
      form = ExamForm(instance=exam, subject=exam.subject, professor=limitProf)
      form.fields['id'].widget.attrs['readonly'] = True
      form.fields['special'].widget.attrs['hidden'] = True
      form.fields['subject'].widget.attrs['hidden'] = True
    
    try:
      final=Exam.objects.get(pk=selected_exam).subject
    except:
      final='wakka'
    
  return {"year":final,"profi":profi,"formsubmit":formsubmit,"only_search":False,"professor":professorObj,"form":form,"exam":exam,"info":request.GET.has_key("info"), "win":win}
 
    
@login_required
@render_to('exams/input_exam.htm')
@permission_required('exams.can_input_exam')
def input_exam(request, prof = None):
  
  #print request.user.professor;
  #request.user.professor = Professor.objects.filter(last_name="Orel");
  #print request.user.professor;
  #print request.user;
  #print Exam.objects.all().values('subject');  
  form = InputExamSelection()
  max_year = SubjectYear.objects.values_list('school_year_start').distinct().order_by('-school_year_start')[0];
  #print 'max year prof: ' + str(max_year[0]);
  
  try:
    if request.user.professor:
      prof = request.user.professor
  except:
    pass
  try:
    form.fields['subject'].queryset = SubjectYear.objects.filter(professors = prof, school_year_start=max_year[0]).distinct()
  except:
    #print 'failed!!!!!!!!!!!!!!!!!!!!!!';
    pass;
  try:
    #print "prof name" + str();
    #profi = Professor.objects.get(pk = prof);
    if request.user.professor:
      profi = request.user.professor
  except:
    #try:
    #  profi = Professor.objects.get(pk = prof);
    #except:
      profi = ''
  if request.method == 'POST':
    forma = InputExamSelection(request.POST)
    forma.fields['subject'].queryset = SubjectYear.objects.filter(professors = prof, school_year_start=max_year[0]).distinct()
    if not(forma.is_valid()):
      return {"form":forma, "professor":prof, "profi":profi}
    #for subjectyear in SubjectYear.objects.filter(subject=forma.cleaned_data['subject']):
    prev_exam = Exam.objects.filter(subject=forma.cleaned_data['subject'], date=forma.cleaned_data['examDate'], executor=forma.cleaned_data['executor']).count()
    print "counted prev. exams on same date: " + str(prev_exam)
    if prev_exam > 0:
      return {"saved":"duplicate", "form": form, "professor":prof, "profi":profi}
    
    exam = Exam(
      subject=forma.cleaned_data['subject'], 
      date=forma.cleaned_data['examDate'], 
      time=forma.cleaned_data['examTime'], 
      place=forma.cleaned_data['place'], 
      max_students=forma.cleaned_data['howMany'], 
      created=datetime.date.today(),
      executor=forma.cleaned_data['executor'],
      max_points=forma.cleaned_data['max']
      )
    exam.save()
    #print 'id ' + exam.id
    return {"saved":"succeded", "noduplicate":"true", "form": form, "professor":prof, "profi":profi}
  else:
    return {"form": form, "professor":prof, "profi":profi}


@login_required
@render_to('exams/delete_applications.htm')
def delete_applications(request,student_pk=None):
  deleted = False #if application is deleted
  empty_list = True
  list = []
  only_search = False
  student = None
  referent = False
  warning = False
  step=1
  
  try:
    #get current student
    student = request.user.student
    
  except:
    if student_pk != None:
      student = Student.objects.get(pk = student_pk)
      referent = True
    else:
      only_search = True

  date_today = datetime.datetime.now().date()     

  if student:  
    if request.method == 'POST':
      step = int(request.POST["step"])
      
      queryset_applications = ExamApplication.objects.all().filter(student = student, grade_date = None)
      
      for i in queryset_applications:
        if str(i.pk) in request.POST:
          exam = ExamApplication.objects.get(pk = i.pk)
          if referent:
            if exam.exam.check_exam_date() == False:
              warning = True
          
          if not referent:    
            exam.delete()
            deleted = True
            break
          
          #referent delete application
          elif step == 2:
            step=1
            exam.delete()
            deleted = True
            warning = False
            break
          
          #confirm delete for referent
          elif step == 1:
            step=2
            list = []
            tempList = []
            tempList.append(exam.pk)
            tempList.append(exam.exam.subject.subject)  
            tempList.append(exam.exam.show_professor())
            tempList.append(exam.exam.date)
            
            if exam.exam.time == datetime.time(0,0,0):
              tempList.append("")
            else:  
              tempList.append(exam.exam.time)
              
            tempList.append(exam.exam.place)
            tempList.append(exam.exam.num_students())
            
            list.append(tempList)
            empty_list = False
          
      
    #-----------------------------------------------------------
    
    if step != 2:
      #get applications for exams without grade 
      queryset_applications = ExamApplication.objects.all().filter(student = student, grade_date = None)
      
      list = []
      for i in queryset_applications:
        tempList = []
        
        if not referent:
          if i.exam.check_exam_date() == True:
            tempList.append(i.pk)
          else:
            tempList.append(-1)
        else:
          tempList.append(i.pk)   
          
        tempList.append(i.exam.subject.subject)  
        tempList.append(i.exam.show_professor())
        tempList.append(i.exam.date)
        
        if i.exam.time == datetime.time(0,0,0):
          tempList.append("")
        else:  
          tempList.append(i.exam.time)
          
        tempList.append(i.exam.place)
        tempList.append(i.exam.num_students())
        
        list.append(tempList)
      
      if len(list) > 0:
        empty_list = False
        list.sort(key=lambda x: x[3])
      
    
  return {
    "empty_list":empty_list,
    "list":list,
    "deleted":deleted,
    "only_search":only_search,
    "referent":referent,
    "warning":warning,
    "step_next":step
    }

@permission_required('exams.can_view_grades')
@render_to('exams/list_grades.htm')
def list_grades(request, student = None, subject = None):
  if request.user.get_profile().professor is None:
    raise Http404()
  
  if student:
    try:
      student = Student.objects.get(pk = student)
    except:
      student = None
      subject = None
  if subject:
    try:
      subject = Subject.objects.get(pk = subject)
    except:
      subject = None
  
  grades = None
  subjects = None
  if student and subject:
    grades = ExamApplication.objects.filter(student = student, exam__subject__subject = subject).order_by('exam__date')
  if student:
    subjects = Subject.objects.filter(subjectyear__participants = student, subjectyear__professors = request.user.get_profile().professor).distinct('pk')
  
  return {
    'student': student,
    'subject': subject,
    'subjects': subjects,
    'grades': grades
  }

@login_required
@render_to('exams/view_exams.htm')
def view_exams(request):
  exam_exist = False
  error = False
  
  try:
    #get current student
    student = request.user.student
    year = student.latest_enrollment_sheet.student_year
  except:
    raise Http404()
    error = True
    
  print "letnik: %s" %(year)
  
  if request.method == 'POST':
    step = int(request.POST["step"])
    
    if step == 1:
      form = ViewExams(request.POST)
      
      if not form.is_valid():
        return {"viewExams":form,"step":0,"step_next":1}
      
      get_year = form.cleaned_data['year']
      get_exams = form.cleaned_data['all_exams']
      
      queryset_subject_participant = SubjectParticipant.objects.values('subject').filter(student = student)
      print [i for i in queryset_subject_participant]
      
      queryset_get_year = EnrollmentSheet.objects.values('academic_year').filter(student = student, student_year = get_year).order_by('-academic_year')
      print queryset_get_year
      
      #parse academic year
      if len(queryset_get_year) > 0:
        year = str(queryset_get_year[0])
        year = parse_academic_year(year)  
            
      else:
        year = 0
          
      print year
      
      #all exams for selected year
      queryset_subject_year = SubjectYear.objects.values('subject').filter(pk__in = queryset_subject_participant, school_year_start = year)
      queryset_subject = Subject.objects.filter(pk__in = queryset_subject_year)
      print "Subjects %s" %queryset_subject
      
      if get_exams == '1':
        
        queryset_exam = Exam.objects.filter(subject__subject__pk__in = queryset_subject, date__gt = date(school_start_year(), 10, 1), special = False).order_by('-date')
        
        print "SubjectYear: %s" %(queryset_subject_year)
        print "Exam: %s" %(queryset_exam)
        
      else: #exams that haven't been passed
        
        #get passed exams
        queryset_passed_exams = ExamApplication.objects.values('exam').filter(Q(student = student), (Q(exam_grade__gte = settings.POSITIVE_GRADE_BOUNDARY) | Q(practice_grade__gte = settings.POSITIVE_GRADE_BOUNDARY)))
        print "Passed %s" %queryset_passed_exams
        
        queryset_passed_ex = Exam.objects.values('subject').filter(pk__in = queryset_passed_exams)
        
        #get passed subjects
        queryset_passed_subjects_year = SubjectYear.objects.values('subject').filter(pk__in = queryset_passed_ex)
        queryset_passed_subjects = Subject.objects.filter(pk__in = queryset_passed_subjects_year)
        
        #exclude passed subjects
        print "Passed subjects %s" %queryset_passed_subjects
        if len(queryset_passed_subjects_year) > 0:
          queryset_subject = queryset_subject.exclude(pk__in = queryset_passed_subjects)
       
        #get unpassed exams
        queryset_exam = Exam.objects.filter(subject__subject__pk__in = queryset_subject, date__gt = date(school_start_year(), 10, 1), special = False).order_by('-date')
        
        
      if len(queryset_exam) > 0:
        exam_exist = True    
      
      
      #delete duplicates caused of different subject years
      subject1 = None
      date1 = None
      for i in queryset_exam:
        if i.subject.subject.pk == subject1 and date1 == i.date:
          queryset_exam = queryset_exam.exclude(pk = i.pk)
        subject1 = i.subject.subject.pk 
        date1 = i.date
        
      
      default_time = datetime.time(0,0,0)
      return {
          "error":error,    
          "exam_exist":exam_exist,
          "queryset_exam":queryset_exam,
          "default_time":default_time,
          "step":1,
          "parameters": {
            "step": 1,
            "year": form.cleaned_data["year"],
            "all_exams": form.cleaned_data["all_exams"]
          }
        }
    
    else:
      form = ViewExams()
      form.fields['year'].choices = settings.STUDENT_YEARS[:int(year)]
     
      return {
        "error":error,      
        "viewExams":form,
        "step":0,
        "step_next":1
        }
      
  else:
    
    form = ViewExams()
    form.fields['year'].choices = settings.STUDENT_YEARS[:int(year)]
    return {
      "error":error,      
      "viewExams":form,
      "step":0,
      "step_next":1
      }

#get year from a filed
def parse_academic_year(year):
  counter = 0
  str_year = []
  for i in year:
    if i.isdigit() and counter < 4:
      str_year.append(i)
      counter = counter + 1
  #get academic year    
  year = int("".join(str_year))
  return year

# TODO: This should be in core.utils
def school_start_year():
  date_today = datetime.date.today()
  if date_today.month <10:
    school_year_start = datetime.date(date_today.year-1, 1, 1)
  else:
    school_year_start = date_today
    
  return school_year_start.year    
  
@render_to('exams/delete_exam.htm')  
def delete_exam(request, professor=None, selected_exam=None):
  form = ExamSelection()

  professorObj = None
  try:
    if (request.user.professor):
      professorObj = request.user.professor
      if not professor:
        redirect("/exams/delete_exam/"+str(professorObj.pk)+"/")
  except Exception,e:
    print e
    if not professor:
      return {"only_search":True}
    professorObj = Professor.objects.get(pk = professor )
    
  form.fields['exam'].queryset = Exam.for_professor(professorObj).filter(special=False).order_by("date")
  form.fields["exam"].initial = selected_exam

  exam = None
  if selected_exam:
    exam = Exam.objects.get(pk=selected_exam)
    
    if request.method == 'POST':
      exam.delete()
      return redirect("/exams/delete_exam/"+str(professorObj.pk)+"/"+"?info=1")
    
  return {"only_search":False,"professor":professorObj,"form":form,"exam":exam,"info":request.GET.has_key("info")}
 
def subject_exam_ajax(request,subject_year_id, student_pk=None):
  referent = False
  try:
    #get current student
    student = request.user.student
  except:
    print "except"
    referent = True
    student = request.GET["student"]
  
  print "referentka %s" %referent
  
  date_today = datetime.date.today()
  subject = SubjectYear.objects.get(pk = subject_year_id)
  if not referent:
    #get all future exams
    queryset_exam = Exam.objects.filter(subject__subject=subject.subject, date__gt = date_today, special = False).order_by('date')
    print "Future dates %s" %queryset_exam
  else:
    
    queryset_exam = Exam.objects.filter(subject__subject=subject.subject, date__gt = date(school_start_year(),10,1), special = False).order_by('date')  
    get_student = Student.objects.get(pk = student)
    get_applications = ExamApplication.objects.values('exam').filter(student = get_student, exam__subject__subject = subject.subject)
    get_exams = Exam.objects.filter(pk__in = get_applications)
    #exclude applied exams
    queryset_exam = queryset_exam.exclude(pk__in = get_exams)
    
  if not referent:
    #check if there are more than 3 days until exam
    queryset_exam_temp = queryset_exam
    for i in queryset_exam_temp:
      if i.check_exam_date() == False:
        queryset_exam = queryset_exam.exclude(pk = i.pk)
  
    queryset_exam_temp = queryset_exam
    for i in queryset_exam_temp:
      #check if there are 14 days between 2 applies
      if i.check_14_days(student) == False:
        queryset_exam = queryset_exam.exclude(pk = i.pk)
  
  dict= []
  for i in queryset_exam:
    dict.append({
      "pk": i.pk,
      "date": i.date.strftime('%d.%m.%Y'),
      "executor": i.executor.cooperates_with_str(),         
    })
   
  
  json_serializer = serializers.get_serializer('json')()
  output = json.dumps(dict, ensure_ascii=False)
  return HttpResponse(output, mimetype = 'application/json')
  
def subject_profesor_ajax(request,subject_year_id):
  json_serializer = serializers.get_serializer('json')()
  prof = [x.professor.code for x in Executor.objects.filter(subject_year=subject_year_id)]
  output = json_serializer.serialize(Professor.objects.filter(code__in=prof), ensure_ascii=True)
  return HttpResponse(output, mimetype = 'application/json')
  
def subject_executor_ajax(request,subject_year_id):
  output = []
  sy = SubjectYear.objects.get(pk=subject_year_id)
  sy = sy.executors_choices()
  for s in sy:
    output.append({"id":s[0],"name":s[1]})
  output = json.dumps(output)
  return HttpResponse(output, mimetype = 'application/json')
  
def subject_rating_type_ajax(request,subject_year_id):
  sy = SubjectYear.objects.get(pk=subject_year_id)
  rating_type = sy.rating_type
  output = {"value":rating_type}
  output = json.dumps(output)
  return HttpResponse(output, mimetype = 'application/json')
